<template>
    <div v-if="userInfo">
      <input type="file" class="myfile" ref="myfile" @change="startUploadFile"  name="file" id="file"> 
       <el-avatar  @click="changeAvatar" v-if="userInfo.avatar" :src="userInfo.avatar.replace(/public/,baseURL)"></el-avatar>
       <el-avatar @click="changeAvatar" v-else src="https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png"></el-avatar>
        <!-- <form action=""></form> -->
    </div>
</template>

<script>
import {useStore} from "vuex"
import {computed,ref} from "vue"
import { ajax } from '../service';
export default {
  name:'avatar',
  setup(props){
      const myfile = ref();
      const store = useStore();
      const userInfo = computed(()=>{
        return store.state.userInfo;
      })
      const changeAvatar = ()=>{
          myfile.value.click()
      }
      const startUploadFile =  ()=>{
          var file = myfile.value.files[0];
          console.log(file)
          var data = new FormData();  // 新建一个表单对象 
          data.append("file",file)  // 需要发送给服务器的文件
          ajax.uploadimg(data)
          .then(res=>{
             if(res.code==200){
                var info  = {...store.state.userInfo,avatar:res.avatar};
                console.log(info);
                store.commit("changeUserInfo",info)
             }
          })
      }
      return {
        userInfo,
        myfile,
        changeAvatar,
        startUploadFile
      }
  }
}
</script>

<style lang="scss" >
.myfile{
  display: none;
}
.el-avatar>img{
  width:100%;
}
</style>

